<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col v-if="isEmpty(fundId)" :span="12">
          <el-form-item :label="$t('基金名称')" prop="fundId">
            <MainBodySelect
              v-model="form.fundId"
              parameters="fund"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="!isEmpty(fundId)" :span="12">
          <el-form-item :label="$t('基金名称')" prop="fundId">
            <el-input v-model="form.fundName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('已投标的个数')" prop="investedItemNum">
            <el-input-number
              v-model="form.investedItemNum"
              :placeholder="$t('已投标的个数')"
              :controls="false"
              :precision="0"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('实际募资规模') + $t('金额单位')" prop="fundraisingScale">
            <span slot="label">
              {{ $t('实际募资规模') }}{{ $t('金额单位') }}
              <el-tooltip :content="$t('截止到估值时间，所有出资人累计实缴规模之和')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money
              v-model="form.fundraisingScale"
              unit="w"
              :placeholder="$t('实际募资规模')"
              @change="surplusScaleCalculationHandle"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('已投规模') + $t('金额单位')" prop="investScale">
            <span slot="label">
              {{ $t('已投规模') }}{{ $t('金额单位') }}
              <el-tooltip :content="$t('投资组合列表中累计投资金额合计')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money
              v-model="form.investScale"
              unit="w"
              :placeholder="$t('已投规模')"
              @change="surplusScaleCalculationHandle"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金费用') + $t('金额单位')" prop="fundCost">
            <span slot="label">
              {{ $t('基金费用') }}{{ $t('金额单位') }}
              <el-tooltip :content="$t('截止到估值时间，当前基金费用之和')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="form.fundCost" unit="w" :placeholder="$t('基金费用')" @change="surplusScaleCalculationHandle" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('剩余规模') + $t('金额单位')" prop="surplusScale">
            <span slot="label">
              {{ $t('剩余规模') }}{{ $t('金额单位') }}
              <el-tooltip :content="$t('实际募资规模 - 已投规模 - 基金费用')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money
              v-model="form.surplusScale"
              unit="w"
              :placeholder="$t('剩余规模')"
              @change="valuationAmountCalculationHandle"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目回款总额') + $t('金额单位')" prop="surplusScale">
            <span slot="label">
              {{ $t('投资回款总额') }}{{ $t('金额单位') }}
              <el-tooltip :content="$t('投资组合列表中累计回款总额合计')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money
              v-model="form.totalProjectRefund"
              unit="w"
              :placeholder="$t('投资回款总额')"
              @change="valuationAmountCalculationHandle"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金分配金额') + $t('金额单位')" prop="surplusScale">
            <span slot="label">
              {{ $t('基金分配金额') }}{{ $t('金额单位') }}
              <el-tooltip :content="$t('基金分配功能中，分配金额之和')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money
              v-model="form.fundDistributionAmount"
              unit="w"
              :placeholder="$t('基金分配金额')"
              @change="valuationAmountCalculationHandle"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="portfolioValuationAmount">
            <span slot="label">
              {{ $t('投资组合估值') }}{{ $t('金额单位') }}
              <el-tooltip :content="$t('投资组合列表中基金所占估值合计')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money
              v-model="form.portfolioValuationAmount"
              unit="w"
              :placeholder="$t('投资组合估值')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="sumOfNonProjectIncome">
            <span slot="label">
              {{ $t('非项目收益') }}{{ $t('金额单位') }}
              <el-tooltip :content="$t('基金收益金额合计')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money
              v-model="form.sumOfNonProjectIncome"
              unit="w"
              :placeholder="$t('非项目收益')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('估值时间')" prop="valuationTime">
            <DatePicker
              v-model="form.valuationTime"
              :placeholder="$t('估值时间')"
              @change="changeValuationTimeTip"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('估值金额') + $t('金额单位')" prop="valuationAmount">
            <span slot="label">
              {{ $t('估值金额') }}{{ $t('金额单位') }}
              <el-tooltip :content="$t('实际募资规模 - 已投规模 - 基金费用 - 基金分配金额 + 投资回款总额 + 投资组合估值 + 非项目收益')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money
              v-model="form.valuationAmount"
              unit="w"
              :placeholder="$t('估值金额')"
            ><el-button slot="append" @click="shareValuationCalculationHandle">{{ $t('分摊至出资人') }}</el-button></money>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-show="isRate" :label="$t('汇率')" prop="exchangeRate">
            <el-input-number
              v-model="form.exchangeRate"
              :max="999999999"
              :min="0"
              :precision="4"
              :controls="false"
            />
          </el-form-item>
        </el-col>
        <!--
        <el-col :span="12">
          <el-form-item v-show="isRate" :label="$t('估值金额') + $t('RMB') + $t('金额单位')" prop="valuationAmountRmb">
            <ExchangeRateMoney
              v-model="form.valuationAmountRmb"
              :rate="form.exchangeRate"
              :money="form.valuationAmount"
              :placeholder="$t('估值金额') + $t('RMB') + $t('金额单位')"
              unit="w"
            />
          </el-form-item>
        </el-col>
        -->
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('投资组合') }}</span>
      </div>
      <el-table :data="form.fundValuationDealList" border show-summary :summary-method="getSummaries2">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('标的类型')" align="center" prop="investType" min-width="150" :formatter="formatType" />
        <el-table-column :label="$t('投资标的')" align="center" prop="dealName" min-width="150">
          <template slot-scope="scope">
            <router-link
              target="_blank"
              :to="jumpPage(scope.row)"
              class="link_a"
            >
              {{ $t(scope.row.dealName) }}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column :label="$t('投资金额') + $t('金额单位')" align="center" prop="investAmount" width="150">
          <template slot-scope="scope">
            <money v-model="scope.row.investAmount" unit="w" @blur="changeInvestAmount" @change="changeInvestAmount" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('回款总额') + $t('金额单位')" align="center" prop="totalPayment" width="150">
          <template slot-scope="scope">
            <money v-model="scope.row.totalPayment" unit="w" @change="changeTotalPayment" />
          </template>
        </el-table-column>
        <!--<el-table-column :label="$t('回款本金') + $t('金额单位')" align="center" prop="returnThePrincipal" width="150">-->
        <!--  <template slot-scope="scope">-->
        <!--    <money v-model="scope.row.returnThePrincipal" unit="w" />-->
        <!--  </template>-->
        <!--</el-table-column>-->
        <!--<el-table-column :label="$t('回款收益') + $t('金额单位')" align="center" prop="returnIncome" width="150">-->
        <!--  <template slot-scope="scope">-->
        <!--    <money v-model="scope.row.returnIncome" unit="w" />-->
        <!--  </template>-->
        <!--</el-table-column>-->
        <el-table-column :label="$t('最新估值时间')" align="center" prop="latestValuationTime" width="180">
          <template slot-scope="scope">
            <DatePicker v-model="scope.row.latestValuationTime" :placeholder="$t('最新估值时间')" />
          </template>
        </el-table-column>
        <!--        暂时去掉了，应为债权项目没这个字段-->
        <!--        <el-table-column :label="$t('公司最新估值') + $t('金额单位')" align="center" prop="companyLatestValuation">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ moneyFormat(scope.row.companyLatestValuation, 'w') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column :label="$t('持股比例(%)')" align="center" prop="shareholdingRatio" width="150">
          <template slot-scope="scope">
            <Ratio v-model="scope.row.shareholdingRatio" :max="100" :controls="false" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('基金所占估值') + $t('金额单位')" align="center" prop="fundValuation" width="150">
          <template slot-scope="scope">
            <money v-model="scope.row.fundValuation" unit="w" @change="fundValuationChange" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('项目最新估值') + $t('金额单位')" align="center" prop="dealLatestValuation" width="150">
          <template slot-scope="scope">
            {{ moneyFormat(scope.row.dealLatestValuation, 'w') }} {{ formatCurrency(scope.row.currency) === scope.row.currency ? '' : '(' + $t(formatCurrency(scope.row.currency)) + ')' }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" fixed="right" align="center" width="130">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-circle-plus-outline" @click="addValuationDeal(scope.row)">
              {{ $t('新增') }}
            </el-button>
            <el-button v-hasPermi="['fund:valuation:remove']" size="mini" type="text" icon="el-icon-delete" @click="delValuationDeal(scope.$index)">
              {{ $t('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="area-header" style="margin-top: 10px">
        <span class="area-header-title">{{ $t('未分配的其他收益') }}</span>
      </div>
      <el-table :data="form.fundValuationOtherList" border show-summary :summary-method="getSummaries" class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('资金来源')" align="center" prop="fundSource">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('资金来源') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item
              :prop="'fundValuationOtherList.' + scope.$index + '.fundSource'"
              :rules="fundValuationOtherListRules.fundSource"
            >
              <el-input v-model="scope.row.fundSource" :disabled="scope.row.incomeId" :placeholder="$t('资金来源')" show-word-limit maxlenth="100" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('发生时间')" align="center" prop="operateTime">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('发生时间') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item
              :prop="'fundValuationOtherList.' + scope.$index + '.operateTime'"
              :rules="fundValuationOtherListRules.operateTime"
            >
              <DatePicker
                v-model="scope.row.operateTime"
                :disabled="scope.row.incomeId"
                :placeholder="$t('发生时间')"
              />

            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('金额') + $t('金额单位')" align="center" prop="amount">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item
              :prop="'fundValuationOtherList.' + scope.$index + '.amount'"
              :rules="fundValuationOtherListRules.amount"
            >
              <money
                v-model="scope.row.amount"
                unit="w"
                :disabled="scope.row.incomeId"
                :placeholder="$t('金额')"
                @change="valuationAmountCalculationHandle"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('备注')" align="center" prop="remark">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" :placeholder="$t('备注')" show-word-limit maxlenth="200" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="80">
          <template slot-scope="scope">
            <el-button v-hasPermi="['fund:valuation:remove']" size="mini" type="text" icon="el-icon-delete" @click="delValuationOther(scope.$index, scope.row)">
              {{ $t('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button v-hasPermi="['fund:valuation:edit']" type="primary" icon="el-icon-plus" size="mini" @click="addValuationOther">{{ $t('添加') }}</el-button>
      </div>
      <div class="area-header" style="margin-top: 10px">
        <span class="area-header-title">{{ $t('出资人所占估值') }}</span>
      </div>
      <el-table :data="form.fundValuationLpList" border class="nowrapTable formTable">
        <el-table-column :label="$t('出资人名称')" align="center" prop="investorName">
          <template slot-scope="scope">
            <el-input v-model="scope.row.investorName" disabled :placeholder="$t('出资人名称')" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('认缴时间')" align="center" prop="subscriptionTime">
          <template slot-scope="scope">
            <DatePicker
              v-model="scope.row.subscriptionTime"
              :disabled="true"
              :placeholder="$t('认缴时间')"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('认缴金额') + $t('金额单位')" align="center" prop="subscriptionAmount">
          <template slot-scope="scope">
            <money v-model="scope.row.subscriptionAmount" unit="w" disabled :placeholder="$t('认缴金额')" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('实缴金额') + $t('金额单位')" align="center" prop="paidAmount">
          <template slot-scope="scope">
            <money v-model="scope.row.paidAmount" unit="w" disabled :placeholder="$t('实缴金额')" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('所占估值') + $t('金额单位')" align="center" prop="shareValuation">
          <template slot="header" slot-scope="{}">
            <i style="color: red">*</i>
            <span>{{ $t('所占估值') }}{{ $t('金额单位') }}</span>
            <span slot="label">
              <el-tooltip :content="'(' + $t('出资人实缴金额') + ' / ' + $t('基金实缴金额之和') + ') * ' + $t('估值金额')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fundValuationLpList.' + scope.$index + '.shareValuation'" :rules="{required: true, message:$t('必填信息'), trigger:['blur','change']}">
              <money v-model="scope.row.shareValuation" unit="w" :placeholder="$t('所占估值')" @change="changRmb(scope.$index)">
                <template slot="append">
                  <span class="el-icon-tickets" type="text" @click="changeValuationAmountTip(scope.$index)" />
                </template>
              </money>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column v-if="isRate" :label="$t('所占估值') + $t('RMB') + $t('金额单位')" align="center" prop="shareValuationRmb">
          <template slot-scope="scope">
            <money v-model="scope.row.shareValuationRmb" unit="w" :placeholder="$t('所占估值') + $t('RMB')" />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn has-permi="fund:valuation" :cancel-func="cancel" />
    </div>

    <el-dialog :title="$t('请录入估值时间')" :visible.sync="timeBoxOpen" width="240px" style="margin-top: 20vh" append-to-body :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <div style="height: 100px">
        <DatePicker v-model="boxTime" popper-class="box-message-show-class" style="width: 100% !important;" />
        <div style="position: absolute;padding: 16px;">
          <el-button @click="timeBoxOpen = false">{{ $t('取消') }}</el-button>
          <el-button type="primary" @click="checkBoxTime">{{ $t('确定') }}</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 参股基金估值 -->
    <el-dialog :title="$t('新增估值')" :visible.sync="dealBfValuationOpen" :close-on-click-modal="false" :lock-scroll="false" :destroy-on-close="true" custom-class="dialogForm" append-to-body>
      <dealBfValuationForm ref="dealBfValuationForm" @fundValuationQuickAddData="fundValuationQuickAddData" />
    </el-dialog>

    <!-- 基金估值 -->
    <el-dialog :title="$t('新增估值')" :visible.sync="fundValuationOpen" :close-on-click-modal="false" :lock-scroll="false" :destroy-on-close="true" custom-class="dialogForm" append-to-body>
      <fundValuationFormAdd ref="fundValuationFormAdd" @fundValuationQuickAddData="fundValuationQuickAddData" />
    </el-dialog>
    <!-- 项目通用估值 -->
    <el-dialog :title="$t('新增估值')" :visible.sync="generalValuationDealOpen" :close-on-click-modal="false" :lock-scroll="false" :destroy-on-close="true" custom-class="dialogForm" append-to-body>
      <dealCompanyValuationForm ref="dealCompanyValuationForm" @fundValuationQuickAddData="fundValuationQuickAddData" />
    </el-dialog>
  </div>
</template>

<script>
import {
  // delOtherFundValuation,
  getFundValuation,
  getFundValuationBaseInfo,
  getFundValuationMain,
  saveFundValuation
} from '@/api/fund/valuation/fundValuation'
import MainBodySelect from '@/components/MainBodySelect'
import { getFundBase } from '@/api/fund/fundBase'
import { getSystemCurrency } from '@/api/system/config'
import dealBfValuationForm from '@/views/deal/bf/valuation/dealBfValuationForm.vue'
import fundValuationFormAdd from '@/views/fund/valuation/fundValuationForm.vue'
import Vue from 'vue'
import dealCompanyValuationForm from '@/views/deal/companyvaluation/dealCompanyValuationForm.vue'

export default {
  components: {
    MainBodySelect,
    dealCompanyValuationForm,
    dealBfValuationForm
  },
  data() {
    return {
      // 表单参数
      form: {},
      // 遮罩层
      loading: false,
      // 基金币种
      fundCurr: '',
      // 系统默认币种
      defCurr: '',
      // 是否展示汇率和估值金额rmb
      isRate: false,
      // 基金所占估值之和
      fundValuationSum: 0,
      // 出资人实缴金额之和
      lpTotalAmount: 0,
      // 是否开启watch
      isWatch: false,
      // 表单校验
      rules: {
        fundId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], valuationTime: [
          { required: true, message: this.$t('必填信息'), trigger: ['blur'] }
        ], valuationAmount: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], exchangeRate: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], valuationAmountRmb: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ]
      },
      fundValuationOtherListRules: {
        fundSource: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        operateTime: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        amount: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      currencyOptions: [],
      fundValuationInvestType: [],
      boxTime: undefined,
      timeBoxOpen: false,
      fundId: this.$route.query.id,
      // 参股估值
      dealBfValuationOpen: false,
      // 基金估值
      fundValuationOpen: false,
      // 股权,债券等通过估值表单
      generalValuationDealOpen: false
    }
  },
  watch: {
  },
  created() {
    this.getDicts('currency').then(response => {
      this.currencyOptions = response.data
    })
    this.getDicts('fund_valuation_invest_type').then(response => {
      this.fundValuationInvestType = response.data
    })
    new Vue({})
    Vue.component('fundValuationFormAdd', fundValuationFormAdd)
  },
  methods: {
    // 初始化数据
    init(data) {
      this.initCurr()
      this.loading = true
      if (data != null && data.id !== undefined) {
        getFundValuation(data.id).then(response => {
          this.form = response.data
          this.investSjSum()
          setTimeout(() => {
            this.isWatch = true
          }, 100)
          this.loading = false
        })
      } else {
        this.isWatch = true
        this.reset()
        getFundValuationBaseInfo(this.fundId).then(response => {
          this.form = response.data
          this.fundValuationSum = 0
          this.form.fundValuationDealList.forEach(e => {
            this.fundValuationSum += e.fundValuation
          })
          this.investSjSum()
          this.surplusScaleCalculationHandle()
          this.fundValuationChange()
          // this.shareSumOfNonProjectIncome()
          this.openTimeBox()
          this.loading = false
        })
      }
    },
    investSjSum() {
      this.lpTotalAmount = 0
      this.form.fundValuationLpList && this.form.fundValuationLpList.forEach(e => {
        this.lpTotalAmount += e.paidAmount
      })
    },
    openTimeBox() {
      this.timeBoxOpen = true
    },
    checkBoxTime() {
      if (!this.isEmpty(this.boxTime)) {
        this.timeBoxOpen = false
        this.form.valuationTime = this.boxTime
        this.changeValuationTime(this.boxTime)
      } else {
        this.msgError(this.$t('时间不能为空'))
      }
    },
    formatType(row) {
      return this.selectDictLabel(this.fundValuationInvestType, row.investType)
    },
    /** 跳转 **/
    jumpPage(row) {
      if (row.investType === 'fund') {
        return { path: '/fund/fundBasehome', query: { id: row.dealId }}
      } else if (row.investType === 'spv') {
        return { path: '/fund/fundBaseSpvHome', query: { id: row.dealId }}
      } else {
        return {
          path: '/deal/home/dealBaseHome',
          query: { id: row.dealId, dealType: row.investType, companyId: row.companyId, showType: 'deal' }
        }
      }
    },
    /** 自动合计已投规模金额 **/
    changeInvestAmount(val) {
      if (this.isEmpty(val)) {
        val = 0
      }
      var temp = 0
      this.form.fundValuationDealList.forEach(item => {
        temp += this.formatNum(item.investAmount)
      })
      this.form.investScale = temp
    },
    changeTotalPayment() {
      this.form.totalProjectRefund = 0
      this.form.fundValuationDealList && this.form.fundValuationDealList.forEach(item => {
        if (item.totalPayment) {
          this.form.totalProjectRefund += item.totalPayment
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        fundId: this.fundId,
        investedItemNum: undefined,
        fundraisingScale: undefined,
        investScale: undefined,
        fundCost: undefined,
        surplusScale: undefined,
        valuationTime: undefined,
        valuationAmount: undefined,
        portfolioValuationAmount: undefined,
        sumOfNonProjectIncome: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        exchangeRate: undefined,
        valuationAmountRmb: undefined,
        fundValuationDealList: [],
        fundValuationOtherList: [],
        fundValuationLpList: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      if (this.$parent.$parent.fundValuationOpen !== undefined) {
        this.$parent.$parent.fundValuationOpen = false
      } else {
        this.$parent.$parent.formOpen = false
        this.$parent.$parent.reset()
      }
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.fundValuationOpen !== undefined) {
       this.$parent.$parent.fundValuationOpen = false
      } else {
        this.$parent.$parent.formOpen = false
        // 刷新list页面
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      // 如果币种一样汇率1 rmb等于金额
      if (!this.isRate) {
        this.form.exchangeRate = 1
        this.form.valuationAmountRmb = this.form.valuationAmount
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveFundValuation(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              // 从基金估值处快速添加
              this.fundValuationQuickAdd()
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    /** 基金估值页面快速添加 **/
    fundValuationQuickAdd() {
      console.clear()
      if (this.$parent.$parent.fundValuationQuickAddData !== undefined) {
        // 该方法调用时, 该页面为基金估值页面, 且为快速添加
        var fundId = this.$route.query.id
        var ratio = 0
        var valuationMoney = 0
        this.form.fundValuationLpList && this.form.fundValuationLpList.forEach(item => {
          if (item.investorId === fundId) {
            ratio = (this.formatNum(item.shareValuation) / this.formatNum(this.form.valuationAmount)) * 100
            valuationMoney = this.formatNum(item.shareValuation)
          }
        })
        const data = {
          dealId: this.form.fundId,
          latestValuationTime: this.form.valuationTime,
          dealLatestValuation: this.form.valuationAmount,
          shareholdingRatio: ratio,
          fundValuation: valuationMoney,
          type: 'fund'
        }
        this.$emit('fundValuationQuickAddData', data)
      }
    },
    // 添加 其它资金/未分配的其他收益 table行
    addValuationOther() {
      const row = {
        id: undefined,
        valuationId: undefined,
        fundSource: undefined,
        operateTime: undefined,
        amount: undefined,
        remark: undefined
      }
      if (!(this.form.fundValuationOtherList instanceof Array)) {
        this.$set(this.form, 'fundValuationOtherList', [])
      }
      this.$nextTick(() => {
        this.form.fundValuationOtherList.push(row)
      })
    },
    /** 投资组合不同主体添加估值 **/
    addValuationDeal(row) {
      if (row.investType === 'bf') {
        // 参股
        this.dealBfValuationOpen = true
        this.$nextTick(() => {
          this.$refs.dealBfValuationForm.dealId = row.dealId
          this.$refs.dealBfValuationForm.init(null)
        })
      } else if (row.investType === 'fund') {
        // 基金
        this.fundValuationOpen = true
        this.$nextTick(() => {
          this.$refs.fundValuationFormAdd.fundId = row.dealId
          this.$refs.fundValuationFormAdd.init(null)
          this.$refs.fundValuationFormAdd.form.valuationBackground = '基金估值快速添加'
        })
      } else if (row.investType === 'spv') {
        // spv
        this.msgInfo(this.$t('SPV暂不支持'))
      } else {
        // 股权及其他项目类型
        this.generalValuationDealOpen = true
        this.$nextTick(() => {
          this.$refs.dealCompanyValuationForm.dealId = row.dealId
          this.$refs.dealCompanyValuationForm.init(null)
        })
      }
    },
    /** 参股积基金/项目/基金中快速添加回调方法 **/
    fundValuationQuickAddData(data) {
      console.table([data])
      if (!this.isEmpty(data)) {
        this.form.fundValuationDealList && this.form.fundValuationDealList.forEach(item => {
          if (item.dealId === data.dealId) {
            // 判断新增的估值日期是不是最新的. 如果是最新的则替换数据, 否则不处理
            const currentDate = this.isEmpty(item.latestValuationTime) ? '19800101' : item.latestValuationTime.toString().replaceAll('-', '')
            const newDate = data.latestValuationTime.toString().replaceAll('-', '')
            if (this.formatNum(currentDate) <= this.formatNum(newDate)) {
              item.latestValuationTime = data.latestValuationTime
              item.dealLatestValuation = data.dealLatestValuation
              item.shareholdingRatio = data.shareholdingRatio
              item.fundValuation = data.fundValuation
            }
          }
        })
      }
    },
    // 删除 其它资金/未分配的其他收益 table行
    delValuationOther(index, row) {
      var _this = this
      console.log('删除其他', row)
      _this.form.fundValuationOtherList.splice(index, 1)
      // const id = row.id
      // if (id !== undefined) {
      //   this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
      //     confirmButtonText: this.$t('确定'),
      //     cancelButtonText: this.$t('取消'),
      //     type: 'warning'
      //   }).then(() => {
      //     _this.loading = false
      //     return delOtherFundValuation(id)
      //   }).then(() => {
      //     _this.form.fundValuationOtherList.splice(index, 1)
      //     return _this.msgSuccess(this.$t('删除成功'))
      //   }).catch(() => {
      //     _this.loading = false
      //   })
      // } else {
      //   this.form.fundValuationOtherList.splice(index, 1)
      // }
    },
    delValuationDeal(index) {
      this.form.fundValuationDealList.splice(index, 1)
      this.surplusScaleCalculationHandle()
      this.changeInvestAmount()
    },
    // 删除出资人所占估值table行
    delValuationLp(index) {
      this.form.fundValuationLpList.splice(index, 1)
    },
    // 计算投资组合估值总和
    fundValuationChange() {
      var money = 0
      this.form.fundValuationDealList && this.form.fundValuationDealList.forEach(item => {
        money += this.formatNum(item.fundValuation)
      })
      this.form.portfolioValuationAmount = money
    },
    // 剩余规模计算
    surplusScaleCalculationHandle() {
      this.$set(this.form, 'surplusScale', (this.form.fundraisingScale || 0) - (this.form.investScale || 0) - (this.form.fundCost || 0))
      this.valuationAmountCalculationHandle()
    },
    // 估计金额计算
    valuationAmountCalculationHandle() {
      // 计算其他资金金额之和
      let amountSum = 0
      // this.form.surplusScale + this.fundValuationSum + amountSum
      // 基金实缴规模-已投规模-基金费用 + 项目回款总额 - 基金分配金额 + 项目列表中基金所占项目估值之和 + 其他资产收益之和
      amountSum = this.formatNum(this.form.fundraisingScale) - this.formatNum(this.form.investScale) - this.formatNum(this.form.fundCost) + this.formatNum(this.form.totalProjectRefund) - this.formatNum(this.form.fundDistributionAmount)
      // 项目列表中基金所占项目估值之和
      this.form.fundValuationDealList.forEach(item => {
        amountSum += this.formatNum(item.fundValuation)
      })
      // 其他资产收益之和
      this.form.fundValuationOtherList.forEach((e) => {
        if (!e.dealId) {
          amountSum += this.formatNum(e.amount)
        }
      })
      this.$set(this.form, 'valuationAmount', amountSum)
      // 计算非项目收益之和
      // this.shareSumOfNonProjectIncome()
    },
    // 非项目收益总和 / 其他资金去掉项目的 剩下的金呃总额
    // shareSumOfNonProjectIncome() {
    //   var tempMoney = 0
    //   this.form.fundValuationOtherList && this.form.fundValuationOtherList.forEach(item => {
    //     if (item.dealId === undefined || item.dealId === null || item.dealId === '') {
    //       tempMoney += this.formatNum(item.amount)
    //     }
    //   })
    //   this.form.sumOfNonProjectIncome = tempMoney
    // },
    /** 投资组合合计 **/
    getSummaries2(param) {
      const { columns } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 3) {
          var money3 = 0
          this.form.fundValuationDealList && this.form.fundValuationDealList.forEach(item => {
            money3 += this.formatNum(item.investAmount)
          })
          sums[index] = this.moneyFormat(money3, 'w')
        } else if (index === 4) {
          var money4 = 0
          this.form.fundValuationDealList && this.form.fundValuationDealList.forEach(item => {
            money4 += this.formatNum(item.totalPayment)
          })
          sums[index] = this.moneyFormat(money4, 'w')
        } else if (index === 7) {
          var money7 = 0
          this.form.fundValuationDealList && this.form.fundValuationDealList.forEach(item => {
            money7 += this.formatNum(item.fundValuation)
          })
          sums[index] = this.moneyFormat(money7, 'w')
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    /**  其它资金/未分配的其他收益 合计 **/
    getSummaries(param) {
      const { columns } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 3) {
          sums[index] = this.sumMoneySummaries()
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    sumMoneySummaries() {
      var moneySum = 0
      this.form.fundValuationOtherList && this.form.fundValuationOtherList.forEach(item => {
        moneySum += this.formatNum(item.amount)
      })
      return this.moneyFormat(moneySum, 'w')
    },
    formatNum(val) {
      if (val !== undefined && val !== null && val !== '' && !isNaN(val)) {
        if (Number(val)) {
          return parseFloat(val)
        } else {
          return 0
        }
      } else {
        return 0
      }
    },
    formatCurrency(val) {
      const currency = this.currencyOptions.find(obj => obj.dictValue === val)
      if (currency) {
        return currency.dictLabel
      }
      return val
    },
    /** 基金估值变化.同步变化出资人估值的所占估值 **/
    changeValuationAmountTip(index) {
      console.log('基金估值变化')
      this.form.fundValuationLpList.forEach((e, i) => {
        if (i === index) {
          // 所占估值 = (出资人实缴金额 / 基金实缴金额之和) * 估值金额
          if (this.formatNum(this.lpTotalAmount) === 0) {
            e.shareValuation = 0
          } else {
            e.shareValuation = this.formatNum(this.formatNum(e.paidAmount) / this.formatNum(this.lpTotalAmount) * this.formatNum(this.form.valuationAmount))
          }
        }
      })
    },
    // 所占估值计算
    shareValuationCalculationHandle() {
      var _this = this
      this.$confirm(this.$t('确定执行分摊至出资人操作?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        _this.shareValuationCalculationHandleSub()
      })
    },
    shareValuationCalculationHandleSub() {
      if (this.form.fundValuationLpList !== undefined && this.form.fundValuationLpList !== null && this.form.fundValuationLpList.length > 0) {
        var fundValuationSum = 0
        this.form.fundValuationLpList.forEach(item => {
          if (item.paidAmount === undefined || item.paidAmount === null || item.paidAmount === '') {
            item.paidAmount = 0
          }
          fundValuationSum += this.formatNum(item.paidAmount)
        })
        this.form.fundValuationLpList.forEach((e, i) => {
          var money = isNaN(e.paidAmount / fundValuationSum * this.form.valuationAmount) ? 0 : e.paidAmount / fundValuationSum * this.form.valuationAmount
          this.$set(this.form.fundValuationLpList[i], 'shareValuation', money)
        })
      }
    },
    // 初始化币种信息
    async initCurr() {
      await getFundBase(this.fundId).then(res => {
        this.fundCurr = res.data.currency
      })
      await getSystemCurrency().then(res => {
        if (res.code === 200) {
          this.defCurr = res.data
        } else {
          this.msgError(res.msg)
        }
      })
      this.isRate = this.defCurr !== this.fundCurr
    },
    changRmb(index) {
      console.log(this.form.fundValuationLpList[index])
      this.form.fundValuationLpList[index].shareValuationRmb = this.form.fundValuationLpList[index].shareValuation * this.form.exchangeRate
    },
    changRmbAll() {
      if (this.form.exchangeRate !== undefined && this.form.exchangeRate !== '' && this.form.fundValuationLpList !== undefined) {
        for (let i = 0; i < this.form.fundValuationLpList.length; i++) {
          this.changRmb(i)
        }
      }
    },
    // 估值时间发生变化时. 只带当前时间之前的已投项目列表
    changeValuationTimeTip(val) {
      if (!this.isEmpty(val)) {
        var _this = this
        this.$confirm(this.$t('估值时间发生变化时,已填写的数值也会发生变化,是否继续?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(() => {
          _this.changeValuationTime(val)
        }).then(() => {
        }).catch(() => {
        })
      }
    },
    // 根据估值时间获取该时间段前的详细信息
    changeValuationTime(val) {
      this.loading = true
      getFundValuationMain(this.fundId, val).then(response => {
        // 主表
        if (response.data !== null) {
          // 投资组合
          this.form.fundValuationDealList = response.data.fundValuationDealList
          // 其他资金
          this.form.fundValuationOtherList = response.data.fundValuationOtherList
          // 实际募资规模
          this.form.fundraisingScale = response.data.fundraisingScale
          // 基金作为投资主体的实际付款金额的和(已投规模)
          this.form.investScale = response.data.investScale
          // 基金的基金费用之和(基金费用)
          this.form.fundCost = response.data.fundCost
          // 项目回款总额
          this.form.totalProjectRefund = response.data.totalProjectRefund
          // 基金分配金额
          this.form.fundDistributionAmount = response.data.fundDistributionAmount
          // 已投个数据
          this.form.investedItemNum = response.data.investedItemNum
        }

        this.changeInvestAmount()
        // 重新自己算 估值金额
        this.surplusScaleCalculationHandle()
        this.valuationAmountCalculationHandle()
        this.fundValuationChange()
        // this.shareSumOfNonProjectIncome()
        this.loading = false
      }).catch(e => {
        console.info(e)
        this.msgError(this.$t('获取数据时出现错误'))
        this.loading = false
      })
    }
  }
}
</script>
<style scoped lang="scss">
.box-message-show-class {
  width: 100% !important;
}
</style>
